www.gusucode.com > Non-photorealistic Camera工具箱源码matlab程序 > Non-photorealistic Camera/RGBHistMatch.m

    function [ Result] = RGBHistMatch( I,R )
%matchin the histogram of a given colored image i to a reference image r for
%generate the result image 
%%
% Author: Mahmoud Afifi, York University


close all
I_=I; R_=R; %take a backup
Result=zeros(size(I));
for Channel=1:3
if size(R,2)>1
%an image, replace the image with its histogram equalization transformation
if size(R,3)>1  
    R_=R(:,:,Channel);
end
%Calc CDF (G) of the reference image 
[countR,binsR]=imhist(R_);
%pR=countR/(size(R_,1)*size(R_,2));
pR=countR/numel(R_);
else
    %else, the given R is the reference PDF
    pR=R_;
end
G=255*cumsum(pR);
G=round(G);

if size(I,3)>1
    I_=I(:,:,Channel);
end


%Calc the given image's histogram equalization transformation
[S] = HistEquTrans(I_);

%Map S to G
F=zeros(size(G)); %the map (F) where F represents S->G
min=1000000;minIndex=-1;
for i=1:size(S,1)
    for j=1:size(G,1)
        T=abs(S(i,1)-G(j,1));
        if T==0
            minIndex=j;
            break
        elseif T<min
            minIndex=j;
            min=T;
        end    
    end
    F(i,1)=minIndex;
    minIndex=-1;
    min=1000000;
end



%Map the value of mapped S (F) to corresponding pixels in the original image
    result=zeros(size(I_(:)));
    for k=1:size(F,1) 
       indecies=find(I_==k-1);
       result(indecies)=F(k,1);
    end
    
    Result(:,:,Channel)=reshape(uint8(result),size(I_));

end  
Result=uint8(Result);
end

function [s,result]=HistEquTrans(i)
% return the histogram equalization transformation
    L=256;
    if(size(i,3)>1)
        i=rgb2gray(i);
    end
    %reshape the image into single dimension
    temp=i(:);
    [counts,bins]=imhist(temp); %calc histogram of the given image
    p=counts/size(temp,1); %calc PDF of the image
    s=(L-1)*cumsum(p); %calc s=(L-1)*CDF(p)
    s=round(s); %round the float into the nearest integare    
end